import React, { useEffect, useState, useCallback } from 'react'
import { Divider, Empty, InputRef, Pagination, Skeleton } from 'antd'
import { useSearchNote } from '../hooks/useSearchNote.ts'
import Search from 'antd/es/input/Search'
import { Panel } from '@/base/components'
import {
  NoteSearchQueryParams,
  NoteWithRelations,
} from '@/domain/note/types/serviceTypes.ts'
import { NoteItem } from '@/domain/note'

const SearchNoteModal: React.FC = () => {
  const [keyword, setKeyword] = useState('')
  const inputRef = React.createRef<InputRef>()

  // 使用函数式更新确保状态一致性
  const [noteSearchQueryParams, setNoteSearchQueryParams] =
    useState<NoteSearchQueryParams>({
      keyword: '',
      page: 1,
      pageSize: 10,
    })

  // 修改：封装搜索触发逻辑
  const triggerSearch = useCallback((searchKeyword: string) => {
    // 重置页码到第一页
    setNoteSearchQueryParams({
      keyword: searchKeyword,
      page: 1,
      pageSize: 10,
    })
  }, [])

  const handleSearchClick = (value: string) => {
    // 修改：实际触发搜索请求
    triggerSearch(value)
  }

  const handlePageChange = (page: number, pageSize: number) => {
    // 修改：使用函数式更新确保获取最新状态
    setNoteSearchQueryParams((prev) => ({
      ...prev,
      page,
      pageSize,
    }))
  }

  // 修改：添加自动聚焦搜索框
  useEffect(() => {
    inputRef.current?.focus()
  }, [inputRef])

  /**
   * 搜索结果
   */
  const { loading, noteList, pagination } = useSearchNote(noteSearchQueryParams)

  return (
    <Panel>
      {/* 搜索框 */}
      <div className="mt-4">
        <Search
          ref={inputRef}
          placeholder="输入笔记关键词搜索"
          value={keyword}
          // 修改：分离输入更新和搜索触发
          onChange={(e) => setKeyword(e.target.value)}
          onSearch={handleSearchClick}
          enterButton
          allowClear
        />
      </div>
      {/* 搜索结果列表 */}
      <Divider />
      <div className="test-xs my-2 font-medium text-gray-700">搜索结果</div>
      <Divider />
      <Skeleton loading={loading} active paragraph={{ rows: 5 }}>
        {noteList.length > 0 ? (
          <>
            {noteList.map((note: NoteWithRelations) => (
              <NoteItem
                key={note.noteId}
                note={note}
                showOptions={false}
                showAuthor={true}
                showCategory={true}
                showAdminOptions={false}
                toggleIsModalOpen={function (): void {
                  throw new Error('Function not implemented.')
                }}
                handleCollectionQueryParams={function (): void {
                  throw new Error('Function not implemented.')
                }}
                handleSelectedNoteId={function (): void {
                  throw new Error('Function not implemented.')
                }}
              />
            ))}
            <div className="mt-4 flex justify-center">
              <Pagination
                current={noteSearchQueryParams.page}
                pageSize={noteSearchQueryParams.pageSize}
                total={pagination?.total || 0}
                onChange={handlePageChange}
                onShowSizeChange={handlePageChange}
                showSizeChanger
                pageSizeOptions={['10', '20', '50', '100']}
              />
            </div>
          </>
        ) : (
          <Empty
            description={keyword ? '未找到相关笔记' : '请输入关键词搜索笔记'}
            imageStyle={{ height: 100 }}
            className="pt-12"
          />
        )}
      </Skeleton>
    </Panel>
  )
}

export default SearchNoteModal
